<?php

namespace app\api\controller\user;

use PHPMailer\PHPMailer\PHPMailer;
use think\Controller;
use think\Request;

class Base extends Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->UserModel = model('User.User');
        $this->RecordModel = model('User.Record');
    }

    public function register()
    {
        $email = $this->request->param('email', '');
        $password = $this->request->param('password', '');

        // 注册时 赠送积分
        $registerPoint = model('Config')->where('key', 'RegisterPoint')->value('value');

        // 生成密码盐
        $salt = build_ranstr();

        // 密码加密
        $pwd = md5($password . $salt);

        // 封装数据
        $data = [
            'email' => $email,
            'password' => $pwd,
            'salt' => $salt,
            'point' => $registerPoint,
            'sex' => 0,
            'auth' => 0,
            'vip' => 1
        ];

        // 插入数据
        $result = $this->UserModel->validate('common/User/User.vue')->save($data);
        if ($result == false) {
            $this->error($this->UserModel->getError());
        } else {
            $this->success('注册成功', '/user/base/login');
        }
    }

    public function login()
    {
        $params = $this->request->param();
        $User = $this->UserModel->where(['email' => $params['email']])->find();
        if (!$User) {
            $this->error('用户不存在');
        }
        $password = md5($params['password'] . $User['salt']);
        if ($password != $User['password']) {
            $this->error('密码错误');
        }
        $data = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'avatar' => $User['avatar_cdn'],
            'cover' => $User['cover_cdn'],
            'sex' => $User['sex'],
            'sex_text' => $User['sex_text'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'content' => $User['content'],
            'createtime' => $User['createtime'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'content' => $User['content'],
            'region_text' => $User['region_text'],
        ];
        $this->success('登陆成功', '/user/index', $data);
    }

    public function check()
    {
        $userid = $this->request->param('userid');
        $User = model("User.User")->where('id', $userid)->find();
        if (!$User) {
            $this->error('非法登录');
        }
        $data = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'avatar' => $User['avatar_cdn'],
            'cover' => $User['cover_cdn'],
            'sex' => $User['sex'],
            'sex_text' => $User['sex_text'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'content' => $User['content'],
            'createtime' => $User['createtime'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'content' => $User['content'],
            'region_text' => $User['region_text'],
        ];
        $this->success('登陆成功', '/user/base/index', $data);
    }

    // 个人信息修改
    public function profile()
    {
        $params = $this->request->param();
        $user = $this->UserModel->find($params['id']);
        if (!$user) {
            $this->error('用户不存在');
        }
        // 封装数据
        $data = [
            'id' => $params['id'],
            'nickname' => $params['nickname'],
            'sex' => $params['sex'],
            'content' => $params['content']
        ];

        if (!empty($params['code'])) {
            $parentpath = model('Region')->where(['code' => $params['code']])->value('parentpath');
            if (!$parentpath) {
                $this->error('所选地区不存在');
            }
            [$province, $city, $district] = explode(',', $parentpath);
            // $province = $parentpath[0];
            // $city = $parentpath[1];
            // $district = $parentpath[2];

            if ($province) {
                $data['province'] = $province;
            }
            if ($city) {
                $data['city'] = $city;
            }
            if ($district) {
                $data['district'] = $district;
            }
        }

        if (!empty($params['password'])) {
            // 密码盐
            $salt = build_ranstr();
            $data['password'] = md5($params['password'] . $salt);
            $data['salt'] = $salt;
        }

        if (!empty($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
            $avatar = upload('avatar');
            if ($avatar['code'] == 0) {
                $this->error($avatar['msg']);
            }
            $data['avatar'] = $avatar['data'];
        }
        if (!empty($_FILES['cover']) && $_FILES['cover']['size'] > 0) {
            $cover = upload('cover');
            if ($cover['code'] == 0) {
                $this->error($cover['msg']);
            }
            $data['cover'] = $cover['data'];
        }

        // 更新
        $result = $this->UserModel->isUpdate(true)->save($data);
        if ($result == false) {

            if (!empty($data['cover']) && $_FILES['cover']['size'] > 0) {
                @is_file('.' . $data['cover']) && unlink('.' . $data['cover']);
            }
            if (!empty($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                @is_file('.' . $data['avatar']) && unlink('.' . $data['avatar']);
            }

            $this->error('更新失败');
        } else {
            if (!empty($data['cover']) && $_FILES['cover']['size'] > 0) {
                @is_file('.' . $user['cover']) && unlink('.' . $user['cover']);
            }
            if (!empty($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                @is_file('.' . $user['avatar']) && unlink('.' . $user['avatar']);
            }

            $User = $this->UserModel->find($params['id']);

            $UserData = [
                'id' => $User['id'],
                'email' => $User['email'],
                'nickname' => $User['nickname'],
                'avatar' => $User['avatar_cdn'],
                'cover' => $User['cover_cdn'],
                'sex' => $User['sex'],
                'sex_text' => $User['sex_text'],
                'province' => $User['province'],
                'city' => $User['city'],
                'district' => $User['district'],
                'createtime' => $User['createtime'],
                'content' => $User['content'],
                'point' => $User['point'],
                'vip' => $User['vip'],
                'auth' => $User['auth'],
                'region_text' => $User['region_text']
            ];
            
            $this->success('更新成功', '/user/index', $UserData);
        }
    }

    // 邮箱认证
    public function code()
    {
        $userid = $this->request->param('userid');
        $email = $this->request->param('email');
        // halt($userid);
        $user = $this->UserModel->find($userid);
        if (!$user) {
            $this->error('该用户不存在');
        }
        if ($email != $user['email']) {
            $this->error('该邮箱不存在');
        }
        $code = build_ranstr(4);
        session($userid, $code);
        // halt(session($userid));
        $content = "验证码：{$code}";
        $mail = new PHPMailer(true);
        // 开启SMTP服务
        $mail->isSMTP(true);
        // SMTP服务器  qq邮箱=>  smtp.qq.com
        $mail->Host = "smtp.163.com";
        // 开启认证
        $mail->SMTPAuth = true;
        // 开启支持html发送
        $mail->isHTML(true);
        // 账号
        $mail->Username = 'yjh023873@163.com';
        // 密码 => 开启SMTP时的授权码
        $mail->Password = 'NAXJCXKALSCDWBXD';
        // 端口   服务器需要465端口
        $mail->Port = 465;
        // 协议
        $mail->SMTPSecure = 'ssl';
        // 发件邮箱
        $mail->From = 'yjh023873@163.com';
        // 发件人名字
        $mail->FromName = 'ASK论坛';
        // 接收回复邮箱
        $mail->addReplyTo('yjh023873@163.com', 'NAXJCXKALSCDWBXD');
        // 收件人
        $mail->addAddress($user['email'], $user['nickname']);

        // 邮箱主题
        $mail->Subject = '账号认证';
        // 设置多少个字符换行  80字符
        $mail->WordWrap = 80;
        // 发送内容
        $mail->msgHTML($content);
        // 发送
        $res = $mail->send();
        if ($res === false) {
            $this->error('发送邮件失败');
        } else {
            $this->success('发送邮件成功');
        }
    }

    // 消费记录
    public function recordList () {
        $userid = $this->request->param('userid');
        $timer = $this->request->param('timer');
        $data = $this->RecordModel->whereOr('state', 'in','4,5')->where(['userid' => $userid])
        ->where('FROM_UNIXTIME(createtime,"%Y-%m")="'. $timer .'"')->select();
        if (!$data) {
            $this->error('查询失败');
        }
        $this->success('查询成功', null, $data);
    }

    // 获取用户 积分 信息
    public function getPoint () {
        $userid = $this->request->param('id');
        $point = model("User.User")->where('id', $userid)->value("point");
        // halt($point); 
        if (!$point) {
            $this->error('查询失败', null, 0);
        }
        $this->success('查询成功', null, $point);
    }

    // 充值
    public function addPoint () {
        $userid = $this->request->param('id');
        $point = $this->request->param('point');
        $user = model("User.User")->where('id', $userid)->find();
        if (!$user) {
            $this.error("请先登录");
        }
        if ($point < 0) {
            $this->error('充值金额不能为负数!');
        }

         // 开启事务
        //  $this->UserModel->startTrans();
        //  $this->RecordModel->startTrans();

        // 更新用户积分
        // $pointValue = bcadd($user['point'], $point);
        // $data = [
        //     "id" => $userid,
        //     "point" => $pointValue
        // ];
        
        // $PointState = model("User.User")->isUpdate(true)->save($data);
        // if ($PointState == false) {
        //     $this->error('充值失败');
        // }

        // 新增用户消费表数据
        $RecordData = [
            "userid" => $userid,
            "point" => $point,
            "state" => 3,
            "flag" => 0,
            "content" => "您于" . date('Y-m-d H:i', time()) . "【充值】了" . $point . "积分，等待审核。" 
        ];
        $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);
        if ($RecordStatus == false) {
            // $this->UserModel->rollback();
            $this->error($this->RecordModel->getError());
        }
        $this->success('等待审核', null, null);
        // if ($PointState == false || $RecordStatus == false) {
        //     $this->UserModel->rollback();
        //     $this->RecordModel->rollback();
        //     $this->error('充值失败', null, null);
        // } else {
        //     $this->UserModel->commit();
        //     $this->RecordModel->commit();
        //     $this->success('等待审核', null, null);
        // }

    }

    // 获取当日充值金额
    public function RechargeToday () {
        $userid = $this->request->param('id');
        $point = $this->RecordModel->whereTime('createtime','today')
        ->where(['userid' => $userid, 'state' => 3])->select();
        // halt($point);
        if (!$point) {
            $this->error('暂无数据');
        }
        $total = 0;
        foreach($point as $item) {
            $total = bcadd($item['point'], $total);
        }
        if ($total > 10000) {
            $this->error('充值金额已到达上限', null, $total);
        }
        $this->success('查询成功', null, $total);

    }

    // 充值记录
    public function RechargeList () {
        $userid = $this->request->param('userid');
        $timer = $this->request->param('timer');
        $data = $this->RecordModel->where(['userid' => $userid, 'state' => 3])
        ->where('FROM_UNIXTIME(createtime,"%Y-%m")="'. $timer .'"')->select();
        if (!$data) {
            $this->error('查询失败');
        }
        $this->success('查询成功', null, $data);
    }

    // 签到
    public function onSign () {
        $userid = $this->request->param('id');
        $user = $this->UserModel->find($userid);
        if (!$user) {
            $this->error('请先登录');
        } 
        
        // 查询今天是否签到
        $sing = $this->RecordModel->whereTime('createtime', 'today')->where(['userid' => $userid, 'state' => 4])->find();
        if ($sing) {
            $this->error('您已签到了', null, 0);
        }
        /**
         * 消费记录表 新增一条记录
         */
        // 开启事务
        $this->UserModel->startTrans();
        $this->RecordModel->startTrans();

        // 获取到签到的积分
        $signPoint = model('config')->where(['key' => 'SignPoint'])->value('value');

        // 用户的积分加上签到的积分
        $Point = bcadd($user['point'], $signPoint);
        // 更新数据
        $UserData = [
            'id' => $userid,
            'point' => $Point
        ];
        $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);
        if ($UserStatus == false) {
            $this->error('签到失败', null, 0);
        }
        // 消费记录
        $RecordData = [
            'userid' => $userid,
            'point' => $signPoint,
            'content' => "您在【" . date('Y-m-d H:i', time()) . "】通过【签到】获取了{$signPoint}积分",
            'state' => 4
        ];

        $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);
        if ($RecordStatus == false) {
            $this->UserModel->rollback();
            $this->error($this->RecordModel->getError(), null, 0);
        }
        if ($UserStatus == false || $RecordStatus == false) {
            $this->UserModel->rollback();
            $this->RecordModel->rollback();
            $this->error('签到失败', null, 0);
        } else {
            $this->UserModel->commit();
            $this->RecordModel->commit();
            $this->success('签到成功', null, 1);
        }
    }

    // 检查是否已经签到 
    public function isSign() {
        $userid = $this->request->param('id');
        $user = $this->UserModel->find($userid);
        if (!$user) {
            $this->error('请先登录');
        } 
        
        // 查询今天是否签到
        $sing = $this->RecordModel->whereTime('createtime', 'today')->where(['userid' => $userid, 'state' => 4])->find();
        if ($sing) {
            $this->error('您已签到了', null, true);
        }
        $this->success('您未签到', null, false);
    }

    public function oncheck() {
        $userid = $this->request->param('userid');
        $code = $this->request->param('code');
        $user = $this->UserModel->find($userid);
        if(!$user) {
            $this->error('该用户不存在');
        }
        $check = strtolower(session($user['id']));
        $code = strtolower($code);
        // halt($check . '===' . $code);
        if ($code != $check) {
            $this->error('验证码错误');
        }
        $data = [
            'id' => $user['id'],
            'auth' => 1
        ];
        $res = $this->UserModel->isUpdate(true)->save($data);
        if ($res == false) {
            $this->error('验证失败');
        }
        $this->success('验证成功');
    }
}
